import {
  PageContainer,
  DragSortTable,
  ProTable,
} from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Popconfirm,
  InputNumber,
  Form,
  Space,
  message,
  Drawer,
} from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import QRCode from "qrcode.react";
import Https from "@/utils/Https";
import { PlusOutlined } from "@ant-design/icons";

const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [open, setOpen] = useState(false);
  const [visible, setVisible] = useState(false);
  const [codeVisible, setCodeVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [QRCodeUrl, setQRCodeUrl] = useState("");
  const [titleType, setTitleType] = useState(0);
  const [form] = Form.useForm();
  const actionRef = useRef();
  const actionRef2 = useRef();

  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
  }, []);

  const editInfo = async (obj) => {
    let res: any = await Https.get(
      "/content/exam/detail",
      { id: obj.id },
      true
    );
    if (res.code == 200 && res.data) {
      form.setFieldsValue({ ...res.data });
    }
    let result: any = await Https.get(
      "/content/exam/findQuestions",
      { id: obj.id },
      true
    );
    if (result.code == 200 && result.data) {
      setDataSource(result.data);
    }
    setTitleType(1);
    setOpen(true);
  };
  const handleDragSortEnd = (
    beforeIndex: number,
    afterIndex: number,
    newDataSource: any
  ) => {
    setDataSource(newDataSource);
  };
  const deleteQuestion = (params) => {
    let result = dataSource.filter((s) => s.id !== params.id);
    setDataSource(result);
  };
  const changeCanvasToPic = () => {
    const canvasImg = document.getElementById("qrCode"); // 获取canvas类型的二维码
    const img = new Image();
    img.src = canvasImg.toDataURL("image/png"); // 将canvas对象转换为图片的data url
    const downLink = document.createElement("a");
    downLink.href = img.src;
    downLink.download = "二维码"; // 图片name
    downLink.click();
  };

  const getScore = (list, key) => {
    let keyList = list.map((l) => (l[key] ? l[key] : 0));
    let num = 0;
    keyList.forEach((l) => {
      num += typeof l === "number" ? l : Number(l);
    });
    return num;
  };

  const handleSelectRowsOk = () => {
    dataSource.push(...selectedRows); //或者arr1 = [...arr1,...arr2]
    //去重
    const strings = dataSource.map((item) => JSON.stringify(item));
    const removeDupList = [...new Set(strings)]; //也可以使用Array.from(new Set(strings))
    const result = removeDupList.map((item) => JSON.parse(item));
    setDataSource(result);
    setVisible(false);
  };
  const rowSelectChange = (selectedRowKeys, selectedRows, info) => {
    setSelectedRows(selectedRows);
    setSelectedRowKeys(selectedRowKeys);
  };
  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
      },
    });
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    width: 250,
    hideInSearch: true,
    render: (_, record) => {
      const _status = parseInt(record.status, 10);
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          {_status === 0 ? (
            <Popconfirm
              title="确定要下架吗?"
              onConfirm={() =>
                toggleState({
                  ...record,
                  status: "1",
                })
              }
            >
              <Button type="link" danger>
                下架
              </Button>
            </Popconfirm>
          ) : (
            <Button
              type="link"
              onClick={() =>
                toggleState({
                  ...record,
                  status: "0",
                })
              }
            >
              上架
            </Button>
          )}
          <Button
            type="link"
            onClick={() => {
              setQRCodeUrl(record.appUrl);
              setCodeVisible(true);
            }}
          >
            小程序码
          </Button>
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    if (dataSource.length == 0) {
      message.error("至少新增一个试卷题目");
      return;
    }
    let objList = [];
    dataSource.map((e) => {
      objList.push(e.id);
    });
    dispatch({
      type: `${namespace}/submitItem`,
      params: {
        ...res,
        examSort: res.examSort ? res.examSort : 0,
        questionList: objList.join(","),
      },
      callback: () => {
        form.resetFields();
        setOpen(false);
        actionRef.current?.reload();
      },
    });
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setTitleType(0);
              form.resetFields();
              setDataSource([]);
              setOpen(true);
            }}
          >
            新建试卷
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        pagination={{
          showSizeChanger: true,
        }}
        scroll={{ x: 1500 }}
        rowKey="id"
        columns={calcColumns({ operate })}
      />

      <Drawer
        open={open}
        title={titleType ? "编辑试卷" : "新建试卷"}
        forceRender
        width="60%"
        onClose={() => setOpen(!open)}
        extra={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
        footer={null}
      >
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ examSort: 0 }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="试卷名称"
            name="examName"
            rules={[
              { required: true, message: "请输入试卷名称,长度不超过30个字" },
            ]}
          >
            <Input maxLength={30} placeholder="请输入试卷名称" showCount />
          </Form.Item>
          <Form.Item label="显示顺序" name="examSort">
            <InputNumber
              min={0}
              max={10000}
              precision={0}
              controls={false}
              style={{ width: "100%" }}
              placeholder="请输入显示顺序,输入的值越大，展示越靠前"
            />
          </Form.Item>
          <Form.Item
            label="试卷描述"
            name="examDesc"
            rules={[{ required: true, message: "请输入试卷描述" }]}
          >
            <Input.TextArea
              maxLength={100}
              placeholder="请输入至少5个字符,限100字"
            />
          </Form.Item>
        </Form>
        <div style={{ padding: "0 76px" }}>
          <DragSortTable
            headerTitle={`共有 ${dataSource.length} 道考题   总分值 ${getScore(
              dataSource,
              "score"
            )} 分`}
            toolBarRender={() => [
              <Button
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                  actionRef2.current?.reload();
                  setVisible(true);
                }}
              >
                新增题目
              </Button>,
            ]}
            columns={[
              {
                title: "排序",
                dataIndex: "sort",
                width: 60,
                className: "drag-visible",
                hideInSearch: true,
              },
              {
                title: "题目ID",
                dataIndex: "id",
                className: "drag-visible",
                hideInSearch: true,
              },
              {
                title: "题目名称",
                dataIndex: "questionStem",
              },
              {
                title: "题目分值",
                dataIndex: "score",
                hideInSearch: true,
              },
              {
                title: "操作",
                fixed: "right",
                dataIndex: "status",
                align: "center",
                hideInSearch: true,
                render: (_, row) => (
                  <Button type="link" onClick={() => deleteQuestion(row)}>
                    删除
                  </Button>
                ),
              },
            ]}
            search={false}
            options={false}
            rowKey="id"
            scroll={{ y: 300 }}
            pagination={false}
            dataSource={dataSource}
            dragSortKey="sort"
            onDragSortEnd={handleDragSortEnd}
          />
        </div>
      </Drawer>
      <Modal
        open={visible}
        title="新增考题"
        forceRender
        width="60%"
        onCancel={() => setVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setVisible(false)}>取消</Button>
            <Button
              onClick={handleSelectRowsOk}
              loading={submitLoading}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        {visible && (
          <ProTable
            cardBordered
            options={false}
            headerTitle={`共有 ${
              selectedRows.length
            } 道考题   总分值 ${getScore(selectedRows, "score")} 分`}
            actionRef={actionRef2}
            rowSelection={{
              onChange: rowSelectChange,
              selectedRowKeys,
            }}
            pagination={{
              showSizeChanger: true,
            }}
            rowKey="id"
            request={async (params) => {
              return await dispatch({
                type: `${namespace}/queryQuestionTable`,
                params,
              });
            }}
            scroll={{ y: 300 }}
            columns={[
              {
                title: "题目ID",
                dataIndex: "id",
                hideInSearch: true,
              },
              {
                title: "题目名称",
                dataIndex: "questionStem",
              },
              {
                title: "题目分值",
                dataIndex: "score",
                hideInSearch: true,
              },
            ]}
          />
        )}
      </Modal>
      <Modal
        open={codeVisible}
        title="小程序码"
        forceRender
        width={600}
        onCancel={() => setCodeVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setCodeVisible(false)}>关闭</Button>
          </Space>
        }
      >
        <div
          style={{ width: "100%", textAlign: "center", marginBottom: "20px" }}
        >
          <QRCode
            id="qrCode"
            style={{ textAlign: "center" }}
            value={QRCodeUrl} //value参数为生成二维码的链接
            size={200} //二维码的宽高尺寸
            fgColor="#000000" //二维码的颜色
          />
        </div>

        <div style={{ width: "100%", textAlign: "center" }}>
          <Button type="primary" onClick={changeCanvasToPic}>
            保存到本地
          </Button>
        </div>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
